package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.*;
import com.drcoffee.drcoffeemall.mapper.BsUserMapper;
import com.drcoffee.drcoffeemall.service.BsUserService;
import com.drcoffee.drcoffeemall.util.CreatJwtUtil;
import com.drcoffee.drcoffeemall.util.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(rollbackFor = Exception.class)
//@DS("mysql")
public class BsUserServiceImpl implements BsUserService {
    @Autowired
    BsUserMapper bsUserMapper;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;


    /*
     * 登录校验
     * */
    @Override
    public Result login(BsUser bsUser) throws GeneralSecurityException {
        try {
            Map<String, Object> resultMap = new HashMap<>();
            // 解密密码
            bsUser.setPassword(RSAUtil.decrypt(bsUser.getPassword()));
            BsUser selBsUser = bsUserMapper.login(bsUser);
            if (selBsUser == null) {
                return new Result(2, "SUCCESS", "账号或密码错误", null);
            } else {
                selBsUser.setPassword(null);
                String token = CreatJwtUtil.getoken(selBsUser);
                redisTemplate.opsForValue().set(token, selBsUser, 30 * 60, TimeUnit.SECONDS);
                List<BsPurviewType> tab = getTab(selBsUser.getId());
                System.out.println(tab);
                resultMap.put("token", token);
                resultMap.put("user", selBsUser);
                resultMap.put("tab", tab);
                return new Result(1, "SUCCESS", "登录成功", resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    public List<BsPurviewType> getTab(Integer id) {
        try {

            // 根据用户ID查询角色
            List<BsRole> bsRoleList = bsUserMapper.getBsRoleByUser(id);

            // 根据查询BsPurviewType
//            List<BsPurviewType> bsPurviewTypeList = bsUserMapper.getBsPurviewType(id);
            List<BsPurviewType> bsPurviewTypeList = bsUserMapper.getBsPurviewType(bsRoleList);
            System.out.println(bsPurviewTypeList);


            List<BsPurviewType> new_bsPurviewTypeList = new ArrayList<>();
            List<BsPurview> new_bsPurviewList = new ArrayList<>();

            for (BsRole bsRole : bsRoleList) {
                // 根据角色ID查询权限
                List<BsPurview> bsPurviewByRole = bsUserMapper.getBsPurviewByRole(bsRole.getId());
                System.out.println(bsPurviewByRole);
                for (BsPurviewType purviewType : bsPurviewTypeList) {
                    System.out.println(purviewType);
                    for (BsPurview bsPurview : bsPurviewByRole) {
                        System.out.println(bsPurview);
                        // 判断权限TypeId添加到新的List
                        if (bsPurview.getType_id() == purviewType.getId()) {
                            System.out.println(bsPurview.getType_id() == purviewType.getId());
                            new_bsPurviewList.add(bsPurview);
                        }
                    }
                    purviewType.setBsPurviewList(new_bsPurviewList);
                    new_bsPurviewTypeList.add(purviewType);
                    new_bsPurviewList = new ArrayList<>();
                    System.out.println(new_bsPurviewList);
                }
            }
            return new_bsPurviewTypeList;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    /* 删除Token */
    @Override
    public boolean removeToken(String Token) {
        redisTemplate.delete(Token);
        Object obj = redisTemplate.opsForValue().get(Token);
        return obj == null;
    }

    /* 更新Token有效期 */
    @Override
    public void renewalToken(String Token) {
        redisTemplate.expire(Token, 30 * 60, TimeUnit.SECONDS);
    }

    /* 校验Token */
    @Override
    public boolean verifyToken(String Token) {
        BsUser tokenUser = (BsUser) redisTemplate.opsForValue().get(Token);
        if (tokenUser != null) {
            return getBsUserByAccount(tokenUser.getAccount()).getObject() != null;
        }
        return false;
    }

    /* 根据账号查询用户 */
    public Result getBsUserByAccount(String account) {
        try {
            BsUser bsUser = bsUserMapper.getBsUserByAccount(account);
            bsUser.setPassword(null);
            return new Result(1, "SUCCESS", "", bsUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "SUCCESS", "", null);
        }
    }

    @Override
    public Result getBsUser(String search) {
        try {
            List<BsUser> bsUserList = bsUserMapper.getBsUser("%" + search + "%");
            return new Result(1, "SUCCESS", "", bsUserList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getBsRoleByUser(Integer id) {
        try {
            List<BsRole> bsRoleList = bsUserMapper.getBsRoleByUser(id);
            return new Result(1, "SUCCESS", "", bsRoleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getAllBsRole() {
        try {
            List<BsRole> bsRoleList = bsUserMapper.getAllBsRole();
            return new Result(1, "SUCCESS", "", bsRoleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getAllBsPurview() {
        try {
            List<BsPurviewType> bsPurviewTypeList = bsUserMapper.getAllBsPurviewType();
            List<BsPurview> bsPurviewList = bsUserMapper.getAllBsPurview();

            Map<String, Object> data = new HashMap<>();
            data.put("bsPurviewTypeList", bsPurviewTypeList);
            data.put("bsPurviewList", bsPurviewList);

            return new Result(1, "SUCCESS", "", data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /*
     * 名称:role_name
     * 角色ID:role_id
     * 权限ID:purview_ids
     * 操作类型:type
     * */
    @Override
    public Result setPurviewByRole(Map<String, Object> role) {
        try {
            String role_name = (String) role.get("role_name");
            Integer role_id = (Integer) role.get("role_id");
            List<Integer> purview_ids = (List) role.get("purview_ids");
            Integer type = (Integer) role.get("type");

            if (type == 1) {

                BsRole bsRole = new BsRole();
                bsRole.setRole_name(role_name);
                bsRole.setStatus("Y");
                // 添加角色
                bsUserMapper.addRole(bsRole);
                System.out.println(bsRole.getId());
                // 绑定角色与权限关系
                bsUserMapper.addRolePurview(bsRole.getId(), purview_ids);
                return new Result(1, "添加角色成功", "", null);
            } else {
                // 修改角色
                // 删除绑定关系
                bsUserMapper.deleteRolePurview(role_id);
                if (!purview_ids.isEmpty()) {
                    // 添加新的绑定关系
                    bsUserMapper.addRolePurview(role_id, purview_ids);
                }
                if (!role_name.isEmpty()) {
                    bsUserMapper.updateRolePurview(role_id, role_name);
                }
                return new Result(1, "修改角色成功", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "保存失败", e.getMessage(), null);
        }
    }

    @Override
    public Result deleteRole(Integer role_id) {
        try {
            // 删除角色用户绑定关系
            bsUserMapper.deleteRoleUser(role_id);
            // 删除角色权限绑定关系
            bsUserMapper.deleteRolePurview(role_id);
            // 删除角色
            bsUserMapper.deleteRole(role_id);
            return new Result(1, "删除成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }

    }

    @Override
    public Result addBsUser(BsUser bsUser) {
        try {
            bsUser.setPassword(RSAUtil.decrypt(bsUser.getPassword()));
            Integer bsUserCount = bsUserMapper.getBsUserByAccountCount(bsUser.getAccount());
            if (bsUserCount == 0) {
                bsUserMapper.addBsUser(bsUser);
                return new Result(1, "添加用户成功", "", null);
            } else {
                return new Result(2, "该账号已存在，请修改后再试", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result deleteBsUser(Integer id) {
        try {
            // 删除用户角色绑定关系
            bsUserMapper.deleteUserRoleByUserId(id);
            // 删除用户
            bsUserMapper.deleteBsUser(id);
            return new Result(1, "删除成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result editBsUser(BsUser bsUser) {
        try {
            // 解密密码
            bsUser.setPassword(RSAUtil.decrypt(bsUser.getPassword()));
            bsUserMapper.editBsUser(bsUser);
            return new Result(1, "修改成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result addBsPurview(BsPurview bsPurview) {
        try {
            bsUserMapper.addBsPurview(bsPurview);
            return new Result(1, "添加成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result editBsPurview(BsPurview bsPurview) {
        try {
            bsUserMapper.editBsPurview(bsPurview);
            return new Result(1, "修改成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result deleteBsPurview(Integer id) {
        try {
            bsUserMapper.deleteBsPurview(id);
            return new Result(1, "删除成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result addBsPurviewType(BsPurviewType bsPurviewType) {
        try {
            bsUserMapper.addBsPurviewType(bsPurviewType);
            return new Result(1, "添加成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result editBsPurviewType(BsPurviewType bsPurviewType) {
        try {
            bsUserMapper.editBsPurviewType(bsPurviewType);
            return new Result(1, "修改成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result deleteBsPurviewType(Integer id) {
        try {
            Integer bsPurview_count = bsUserMapper.getBsPurviewByType(id);
            if (bsPurview_count == 0) {
                bsUserMapper.deleteBsPurviewType(id);
                return new Result(1, "删除成功", "", null);
            } else {
                return new Result(2, "该权限组被权限绑定无法删除", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }


    }

    @Override
    public Result setBsUserRole(Map<String, Object> bsUserRole) {
        try {
            Integer user_id = (Integer) bsUserRole.get("user_id");
            List<Integer> role_ids = (List) bsUserRole.get("role_ids");
            // 修改角色
            // 删除绑定关系
            bsUserMapper.deleteUserRole(user_id);
            if (!role_ids.isEmpty()) {
                // 添加新的绑定关系
                bsUserMapper.addUserRole(user_id, role_ids);
            }
            return new Result(1, "修改成功", "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "保存失败", e.getMessage(), null);
        }
    }


    @Override
    public Result getBsPurviewByRole(Integer roleId) {
        try {
            List<BsPurview> bsPurviewList = bsUserMapper.getBsPurviewByRole(roleId);
            return new Result(1, "SUCCESS", "", bsPurviewList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


}
